const path=require('path');
const fs=require('fs');
const bodyParser=require('body-parser');
const app=require('express')();
const create=require('./create.js');
const Tree=require('./tree.js');

app.use(bodyParser());

app.post('/new',(req,res)=>{
    let data=create();
    //console.log(data);
    let tree=new Tree(data);
    tree.save(err=>{
        if(err)throw err;
        res.type('json').send({id:tree._id,rootId:data.rootId});
    });
});

app.get('/:tid/children/:cid',(req,res)=>{
    Tree.findOne({_id:req.params.tid},(err,ret)=>{
        if(err)throw err;
        //console.log(`/${req.params.tid}/children/${req.params.cid}:\n`,ret);
        res.json(ret.ids[req.params.cid]);
    });
});

app.post('/:tid/check',(req,res)=>{
    Tree.findOne({_id:req.params.tid},(err,ret)=>{
        if(err)throw err;

        let ids=ret.ids;
        let children=id=>{
            let tree={id};
            tree.children=ids[id].map(cid=>children(cid));
            return tree;
        };
        let tree=children('root');
        tree=JSON.stringify(tree);
        console.log('tree:\n',tree);

        let root=req.body.root;
        console.log('root:\n',root);

        res.json({pass:root==tree});
    });
});

app.use((req,res)=>{
    res.send(404);
});

app.listen(5000,()=>{
    console.log('Tree@5000----',new Date());
});